#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
    导出招投标表算法提取出来并映射好的联系方式，校验入库同步到联系方式表
    >> 限制条件
        1. 中标单位相关信息列表(biddingWinningInfoList)
        2. 招标单位相关信息列表(biddingPurchasingInfoList)
        3. 招标代理机构信息列表(biddingAgentInfoList)
        4. 项目联系方式(biddingProjectContact)
        以上字段需有contact和nameId
    ~~~~~~~

    :author: wangshx
    :date created: 2022-1-14
    :python version: 2.7
'''

from copy import deepcopy
import sys
import json
from datetime import date, timedelta, datetime
from tabnanny import check

from apscheduler.schedulers.blocking import BlockingScheduler

from base import ExportAndTjBase
from models import MongoQueryConfig
from utils import Utils

reload(sys)
sys.setdefaultencoding('utf-8')


class ExportAndTj(ExportAndTjBase):
    def __init__(self, *args, **kwargs):
        super(ExportAndTj, self).__init__(*args, **kwargs)

    def handle_one_mongo_data(self, record_dic, save_result_dic=None):

        # _id = record_dic.get("_id", "")
        # nameId = record_dic.get("nameId", "")
        biddingWinningInfoList = record_dic.get("biddingWinningInfoList", "")
        biddingPurchasingInfoList = record_dic.get("biddingPurchasingInfoList", "")
        biddingAgentInfoList = record_dic.get("biddingAgentInfoList", "")
        biddingProjectContact = record_dic.get("biddingProjectContact", "")

        def check_data(info_list):
            # 检查是否有contact和nameId
            for info in info_list:
                if info.get('nameId') and info.get('contact'):
                    return True
            return False

        try:
            # 4个字段,只要有一个字段有contact和nameId，就导出这条数据
            if (biddingWinningInfoList and check_data(biddingWinningInfoList)) or \
                    (biddingPurchasingInfoList and check_data(biddingPurchasingInfoList)) or \
                    (biddingAgentInfoList and check_data(biddingAgentInfoList)) or \
                    (biddingProjectContact and check_data(biddingProjectContact)):
                record_dic = Utils.decrypt_one_record(record_dic, need_strf_time=True, need_decrypt=True)
                self.write_dc_f.write(json.dumps(record_dic, ensure_ascii=False) + '\n')

        except Exception as e:
            print("[Exception]:" + str(e))
            pass

        return save_result_dic

    def run(self):
        # source_ls = [

        # ]
        save_result_dic = {

        }

        config = {
            MongoQueryConfig.col_name: 'bidding',
            MongoQueryConfig.filter: {

            },
            MongoQueryConfig.projection: ["_id", "biddingSource", "biddingWinningInfoList", "biddingPurchasingInfoList",
                                          "biddingAgentInfoList", "biddingProjectContact", "create_time",
                                          "import_update_time"],
            # MongoQueryConfig.limit: 10000,
        }
        result_dic = self.get_data_from_mongo(config, save_result_dic)


def run(abs_file_name):
    export_and_tj = ExportAndTj(abs_file_name)
    export_and_tj.main()


def scheduler_run(abs_file_name):
    scheduler = BlockingScheduler()
    scheduler.add_job(func=run, trigger='cron',
                      args=(abs_file_name,),
                      # day_of_week="sun",
                      hour='20', minute='52', id='dd_run')
    scheduler.start()


if __name__ == '__main__':
    file_name = '招投标算法提取的联系方式存量数据'
    # py文件名+file_name+小时时间
    abs_file_name = Utils.generate_abs_path(file_name, current_py_path=__file__, name='wangshx')

    run(abs_file_name)
    # scheduler_run(abs_file_name)
